/*
 * Copyright (c) 2015 Razeware LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import CoreData
import UIKit

protocol PersonPickerDelegate: class {
    func didSelectPerson(person: Person)
}

class PeopleTableViewController: UITableViewController {
//    var coreDataStack: CoreDataStack!
    var people = [Person]()

    // for person select mode
    weak var pickerDelegate: PersonPickerDelegate?
    var selectedPerson: Person?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "People"

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPerson))

        reloadData()
    }

    func reloadData() {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

        let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
        fetchRequest.sortDescriptors = [sortDescriptor]

        do {
            if let results = try CoreDataStack.share.managedObjectContext.fetch(fetchRequest) as? [Person] {
                people = results
                tableView.reloadData()
            }
        } catch {
            fatalError("There was an error fetching the list of people!")
        }
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return people.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "PersonCell", for: indexPath as IndexPath)

        let person = people[indexPath.row]
        cell.textLabel?.text = person.name

        if let selectedPerson = selectedPerson, selectedPerson == person {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if let pickerDelegate = pickerDelegate {
            let person = people[indexPath.row]
            selectedPerson = person
            pickerDelegate.didSelectPerson(person: person)

            tableView.reloadData()
        } else {
            if let devicesTableViewController = storyboard?.instantiateViewController(withIdentifier: "Devices") as? DevicesTableViewController {
                let person = people[indexPath.row]

                devicesTableViewController.coreDataStack = CoreDataStack.share
                devicesTableViewController.selectedPerson = person
                navigationController?.pushViewController(devicesTableViewController, animated: true)
            }
        }

        tableView.deselectRow(at: indexPath as IndexPath, animated: true)
    }

    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return pickerDelegate == nil
    }

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCell.EditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .delete {
            let person = people[indexPath.row]
            CoreDataStack.share.managedObjectContext.delete(person)

            reloadData()
        }
    }

    @objc func addPerson(sender: AnyObject?) {
        // The overall alert controller
        let alert = UIAlertController(title: "Add a Person", message: "Name?", preferredStyle: .alert)

        // The Add button: adds a new person
        let addAction = UIAlertAction(title: "Add", style: .default) { (_) -> Void in
            // If the user entered a non-empty string, add a new Person
            if let textField = alert.textFields?[0],
                let personEntity = NSEntityDescription.entity(forEntityName: "Person", in: CoreDataStack.share.managedObjectContext),
                let text = textField.text, !text.isEmpty {
                let newPerson = Person(entity: personEntity, insertInto: CoreDataStack.share.managedObjectContext)
                newPerson.name = text

                do {
                    try CoreDataStack.share.managedObjectContext.save()
                } catch {
                    CoreDataStack.share.managedObjectContext.delete(newPerson)

                    let alert = UIAlertController(title: "Error", message: "A person's name must be longer than a single character!", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    self.present(alert, animated: true, completion: nil)
                }

                self.reloadData()
            }
        }

        // The Cancel button: does nothing
        let cancelAction = UIAlertAction(title: "Cancel", style: .default) { (_) -> Void in
        }

        // Need one text field in the alert
        alert.addTextField(configurationHandler: nil)

        // Add the two buttons (add and cancel)
        alert.addAction(addAction)
        alert.addAction(cancelAction)

        // Present the alert controller
        present(alert, animated: true, completion: nil)
    }
}
